package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class IssueTeamController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def issueTeamList = IssueTeam.findAll("from IssueTeam where user.username = '${username}'", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = IssueTeam.executeQuery("select count(id) from IssueTeam where user.username = '${username}'")

        respond issueTeamList, model: [issueTeamCount: count[0]]
    }

    def show(IssueTeam issueTeam)
    {
        respond issueTeam
    }

    def create()
    {
        def issue = Issue.findById(params['issue'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (issue?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def issueTeams = IssueTeam.findAllByIssue(issue)
            issueTeams?.each {
                userList -= it?.user
            }
            respond new IssueTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "issue", action: "show", params: [id: issue.id])
            return
        }
    }

    @Transactional
    def save(IssueTeam issueTeam)
    {
        def userList = User.list()
        def issueTeams = IssueTeam.findAllByIssue(issueTeam?.issue)
        issueTeams?.each {
            userList -= it?.user
        }

        if (issueTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (issueTeam.hasErrors())
        {
            //COMMENT THE INFO THEN YOU WILL SEE MIRACLES
            log.info "userList:" + userList

            transactionStatus.setRollbackOnly()
            respond issueTeam.errors, model: [userList: userList], view: 'create'
            return
        }

        issueTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'issueTeam.label', default: 'IssueTeam'), issueTeam.id])
                // redirect issueTeam
                redirect controller: "issue", action: "show", id: issueTeam?.issue?.id
            }
            '*' { respond issueTeam, [status: CREATED] }
        }
    }

    def edit(IssueTeam issueTeam)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)

        TeamRole editTeamRole = TeamRole.findByName('Edit')
        IssueTeam currentIssueTeam = IssueTeam.findByIssueAndUser(issueTeam.issue, user)

        if (issueTeam.issue.user.id == user.id || currentIssueTeam?.teamPermission?.id == editTeamRole.id)
        {
            respond issueTeam, model: [user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect controller: "issue", action: "show", id: issueTeam.issue.id
        }
    }

    @Transactional
    def update(IssueTeam issueTeam)
    {
        if (issueTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (issueTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond issueTeam.errors, view: 'edit'
            return
        }

        issueTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'issueTeam.label', default: 'IssueTeam'), issueTeam.id])
                // redirect issueTeam
                redirect controller: "issue", action: "show", id: issueTeam?.issue?.id
            }
            '*' { respond issueTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(IssueTeam issueTeam)
    {

        if (issueTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        issueTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'issueTeam.label', default: 'IssueTeam'), issueTeam.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'issueTeam.label', default: 'IssueTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchIssueTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String subject = params["subject"]

        String sql = "from IssueTeam as u where u.user.username = '${username}'"
        if (subject)
        {
            sql += " and u.issue.subject like '%${subject}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.issue.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = IssueTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = IssueTeam.executeQuery(countSql)

        respond list, model: [issueTeamCount: count[0], params: params], view: 'index'
    }

    def exportIssueTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String subject = params["subject"]

        String sql = "from IssueTeam as u where u.user.username = '${username}'"
        if (subject)
        {
            sql += " and u.issue.subject like '%${subject}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.issue.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = IssueTeam.findAll(sql)
        def count = IssueTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=issueTeam.${params.extension}")
            List fields = ["issue.contact.fullName", "issue.account.name", "issue.asset.name", "issue.subject", "issue.status.name", "issue.origin.name", "issue.priority.name", "issue.type.name", "issue.reason.name", "issue.description", "issue.createdDate", "issue.modifiedDate"]
            Map labels = ["issue.contact.fullName": "联系人", "issue.account.name": "客户", "issue.asset.name": "资产", "issue.subject": "标题", "issue.status.name": "状态", "issue.origin.name": "来源", "issue.priority.name": "优先级", "issue.type.name": "类型", "issue.reason.name": "原因", "issue.description": "详细说明", "issue.createdDate": "创建时间", "issue.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
